<?php

declare(strict_types=1);

namespace Tools\Commands;

use Hyperf\Command\Command as HyperfCommand;
use Hyperf\Command\Annotation\Command;
use Psr\Container\ContainerInterface;
use Symfony\Component\Console\Input\InputArgument;
use function PHPUnit\Framework\fileExists;

/**
 * @Command
 */
#[Command]
class sync extends HyperfCommand
{
    /**
     * @var ContainerInterface
     */
    protected $container;

    /**
     * 执行的命令行
     *
     * @var string
     */
    protected $name = 'self:sync';

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;

        parent::__construct('self:sync');
    }

    public function configure()
    {
        parent::configure();
        $this->setDescription('同步代码文件到其他服务中,如：php bin/hyperf.php self:sync app/Exception/Handler/ValidationExceptionHandler.php 
 [pcar_server,base_server]');
    }

    protected function getArguments()
    {
        return [
            ['file', InputArgument::REQUIRED, '待同步的文件'],
            ['apps', InputArgument::OPTIONAL, '同步文件的目标应用，多应用采用英文逗号分割，默认所有应用']
        ];
    }

    public function handle()
    {
        // 从 $input 获取 name 参数
        $file = $this->input->getArgument('file');
        $apps = $this->input->getArgument('apps');
        $apps = $apps ? explode(',', $apps) :[];

        $current_app_dir = dirname(__DIR__, 2);
        $micro_dir = dirname(__DIR__, 3);
        $source = $current_app_dir.DIRECTORY_SEPARATOR.$file;
        if(!fileExists($source)){
            $this->line( $source. '文件不存在，请检查文件路径', 'info');
            return;
        }
        if(is_dir($micro_dir)){

            $apps = $apps ?: scandir($micro_dir);

            foreach($apps as $v){
                if(!preg_match('/server$/i', $v)){
                    continue;
                }
                $dest = $micro_dir.DIRECTORY_SEPARATOR.$v.DIRECTORY_SEPARATOR.$file;
                if((is_file($source)) && copy($source, $dest)){
                    $this->line("success：copy to $dest", 'info');
                } else {
                    if(is_dir($source)) {
                        self::copyDir($source, $dest);
                    }
                }
            }
        }

    }

    public static function copyDir($dirSrc,$dirTo)
    {
        if(is_file($dirTo))
        {
            echo $dirTo . '这不是一个目录';
            return;
        }
        if(!file_exists($dirTo))
        {
            mkdir($dirTo);
        }

        if($handle=opendir($dirSrc))
        {
            while($filename=readdir($handle))
            {
                if($filename!='.' && $filename!='..')
                {
                    $subsrcfile=$dirSrc . '/' . $filename;
                    $subtofile=$dirTo . '/' . $filename;
                    if(is_dir($subsrcfile))
                    {
                        self::copyDir($subsrcfile,$subtofile);//再次递归调用copydir
                    }
                    if(is_file($subsrcfile))
                    {
                        copy($subsrcfile,$subtofile);
                    }
                }
            }
            closedir($handle);
        }

    }
}
